//
//  ViewController.swift
//  Test
//
//  Created by youmy on 2018/11/27.
//  Copyright © 2018 youmy. All rights reserved.
//

import UIKit
import RentFree

class ViewController: UIViewController {

    var rentView : YMRentFreeView?
    var depositV:YMRentDepositView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .groupTableViewBackground
        
        let bundle = Bundle(for: YMRentFreeView.classForCoder())
        
        var rentList = [YMRentFreeModel]()
                
        let arr = resoucearrayFromFile(fileName: "rentfree.json", bundle: bundle)
        
        for dic in arr {
            let model = YMRentFreeModel(fromDictionary: dic)
            rentList.append(model)
        }
        
        rentView = YMRentFreeView(frame: CGRect(x: 0, y: 50, width: UIScreen.main.bounds.width, height: 50))
        rentView?.delegate = self
        rentView?.setHeaderContent(title: "租金费用")
        rentView?.isArrowBtn = true
        view.addSubview(rentView!)
        
        rentView?.rentList = rentList
        
        depositV = YMRentDepositView(frame: CGRect(x: 0, y: (rentView?.frame.maxY ?? 0) + 10, width: UIScreen.main.bounds.width, height: 10))
        depositV?.name = "需支付金额"
        depositV?.price = "2106.00"
        depositV?.des = "(到期买断费用￥1200.00，买断时支付)"
        depositV?.priceColor = UIColor(valueRGB: 0xff4230, alpha: 1)
        view.addSubview(depositV!)
    }

    func resoucearrayFromFile(fileName: String, bundle:Bundle? = nil) -> [[String:Any]] {
        
        var jsonPath:String?
        
        if bundle != nil {
            jsonPath = bundle?.path(forResource: fileName, ofType: nil)
        }else{
            jsonPath = Bundle.main.path(forResource: fileName, ofType: nil)
        }
        
        guard let path = jsonPath else {
            return [[String: Any]]()
        }
        
        let data = try? Data(contentsOf: URL(fileURLWithPath: path))
        
        if data != nil {
            let arr = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! Array<Dictionary<String, Any>>
            return arr ?? [[String: Any]]()
        }
        return [[String: Any]]()
    }

}

extension ViewController: YMRentFreeViewDelegate {
    func frameDidChange(view: YMRentFreeView) {
        depositV?.frame.origin.y = (rentView?.frame.maxY ?? 0) + 10
    }
}
